import util from '@/libs/util';
import getDate from '@/util/getDate.js';
import vSwitch from '@/util/switch.vue';

import Cookies from 'js-cookie';

export default {
    components: {
        vSwitch
    },
    name: 'exportable-table',
    data () {
        return {
            columns: [{
                title: '序号',
                key: 'rownum',
                align: 'center',
                width: 60,
                render: (h, params) => {
                    return h('div', {}, ((this.pageIndex - 1) * this.pageSize + params.index + 1));
                }
            }, {
                title: '姓名',
                key: 'name'
            }, {
                title: '性别',
                key: 'gender',
                render: (h, params) => {
                    let texts = '未知';
                    if (params.row.gender === 'MAN') {
                        texts = '男';
                    } else if (params.row.gender === 'WOMAN') {
                        texts = '女';
                    }
                    return h('div', {}, texts);
                }
            }, {
                title: '任职部门',
                key: 'orgname',
                render: (h, params) => {
                    return h('div', {}, (params.row.organize ? params.row.organize.name : ''));
                }
            }, {
                title: '学历',
                key: 'education',
                render: (h, params) => {
                    return h('div', {}, (params.row.education ? params.row.education.name : ''));
                }
            }, {
                title: '教师类型',
                key: 'teachertype',
                render: (h, params) => {
                    return h('div', {}, (params.row.teachertype ? params.row.teachertype.name : ''));
                }
            }, {
                title: '职称',
                key: 'technical',
                render: (h, params) => {
                    return h('div', {}, (params.row.technical ? params.row.technical.name : ''));
                }
            }, {
                title: '手机号',
                key: 'cellphone'
            }, {
                title: '状态',
                key: 'status',
                render: (h, params) => {
                    return h(vSwitch, {
                        props: {
                            vStatus: params.row.status === 1
                        },
                        on: {
                            input: (switchVal) => {
                                this.changeStatus(params.row, switchVal);
                            }
                        }
                    });
                }
            }, {title: '操作',
                key: 'action',
                width: 200,
                align: 'center',
                render: (h, params) => {
                    return h('div', [
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.isRead = true;
                                    this.showEdit(params.row);
                                }
                            }
                        }, '查看'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.isRead = false;
                                    this.showEdit(params.row);
                                }
                            }
                        }, '修改'),
                        h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            on: {
                                click: () => {
                                    this.delete(params.row.id);
                                }
                            }
                        }, '删除')
                    ]);
                }
            }],
            data: [],
            formData: {},
            query: {
                name: '',
                gender: '',
                education: '',
                technical: '',
                teachertype: ''
            },
            formDataRules: {// 添加班级表单验证规则
                name: [
                    { required: true, message: '教师名称不能为空', trigger: 'blur',type: 'string'}
                ],
                cellphone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur', type: 'string'}
                ],
                orgname: [
                    { required: true, message: '请选择任职部门', trigger: 'blur', type: 'string'}
                ],
                gender: [
                    { type: 'string', required: true, message: '请选择性别', trigger: 'blur'}
                ],
                majorIds: [
                    { required: true, message: '请选择专业', trigger: 'blur', type: 'string'}
                ],
                teachertypeid: [
                    { type: 'number', required: true, message: '请选择教师类型', trigger: 'blur'}
                ]
            },
            total: 0,
            load: false,
            pageIndex: 1,
            pageSize: 10,
            orgTree: [],
            majorTree: [],
            ids: [],
            baseuser: JSON.parse(Cookies.get('baseUser')),
            editModal: false,
            mojorModal: false,
            orgModal: false,
            isRead: false,

            sexList: [{id: 'MAN', name: '男'}, {id: 'WOMAN', name: '女'}],
            learnList: [],
            teachertypeList: [],
            positionList: []
        };
    },
    mounted () {
        this.loadDictionaries();
        this.loadList();
        this.loadTree('/busine/major/findAll', {orgid: this.baseuser.orgId}, 'majorTree');
        this.loadTree('/base/organize/findOrgAll', {orgid: this.baseuser.orgId}, 'orgTree');
    },
    methods: {
        loadDictionaries () {
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData({
                CODE: 'LEARN_EXP'
            })).then(res => {
                this.learnList = res.data.data;
            });
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData({
                CODE: 'TEACHER_TYPE'
            })).then(res => {
                this.teachertypeList = res.data.data;
            });
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData({
                CODE: 'POSITION_TYPE'
            })).then(res => {
                this.positionList = res.data.data;
            });
        },
        loadTree (url, formData, treeName) {
            util.ajax.post(url, util.toFormData(formData)).then(res => {
                if (res.data.data) {
                    let tree = [];
                    res.data.data.forEach(item => {
                        if (item.parentid == 0) {
                            tree.push({
                                id: item.id,
                                title: item.name,
                                expand: true,
                                children: []
                            });
                        }
                    });
                    if (tree.length > 0) {
                        this.createTree(tree, res.data.data);
                    }
                    this[treeName] = tree;
                };
            });
        },
        createTree (tree, data) {
            let childTree = [];
            let _this = this;
            tree.forEach(treeItem => {
                childTree = [];
                data.forEach(dataItem => {
                    if (treeItem.id === dataItem.parentid) {
                        let checked = false;
                        if (_this.ids.indexOf(dataItem.id.toString()) > -1) {
                            checked = true;
                        }
                        childTree.push({
                            id: dataItem.id,
                            title: dataItem.name,
                            expand: true,
                            children: [],
                            checked: checked
                        });
                    }
                });
                if (childTree.length > 0) {
                    treeItem.children = childTree;
                    _this.createTree(childTree, data);
                }
            });
        },
        initMajorTree () {
            this.loadTree('/busine/major/findAll', {orgid: this.baseuser.orgId}, 'majorTree');
            this.mojorModal = true;
        },
        loadList () {
            util.ajax.post('/busine/teacher/list', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                name: this.query.name,
                gender: (this.query.gender ? this.query.gender : ''),
                educationid: (this.query.educationid ? this.query.educationid : ''),
                teachertypeid: (this.query.teachertypeid ? this.query.teachertypeid : '')
            })).then(res => {
                this.data = res.data.data.list;
                this.total = res.data.data.total;
            });
        },
        refresh () {
            this.query = {
                name: '',
                gender: '',
                education: '',
                technical: '',
                teachertype: ''
            };
            this.loadList();
        },
        showAdd () {
            this.isRead = false;
            this.formData = {};
            this.ids = [];
            this.editModal = true;
        },
        showEdit (obj) {
            this.formData = {};
            util.ajax.post('/busine/teacher/detail', util.toFormData({
                id: obj.id
            })).then(res => {
                if (res.data.data) {
                    this.formData = res.data.data;
                    this.formData.birthday = util.getDate(this.formData.birthday, 'date');
                    this.formData.teachtime = util.getDate(this.formData.teachtime, 'date');
                    this.formData.orgname = this.formData.organize ? this.formData.organize.name : '';
                    // this.formData.teacherType = this.formData.teachertypeid;
                    this.formData.majorsname = this.formData.majorsName;
                    this.ids = this.formData.majorIds.split(',');
                    this.editModal = true;
                } else {
                    this.$Modal.error({
                        title: '警告',
                        content: '出错了'
                    });
                }
            });
        },
        delete (id) {
            this.$Modal.confirm({
                title: '提示',
                content: '<p>确定删除？</p>',
                onOk: () => {
                    util.ajax.post('/busine/teacher/delete', util.toFormData({
                        id: id
                    })).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            this.$Message.success('删除成功！');
                            this.loadList();
                        }
                    });
                }
            });
        },
        changeStatus (obj, switchVal) {
            this.formData['id'] = obj.id;
            this.formData['status'] = 2;
            if (switchVal) this.formData['status'] = 1;
            util.ajax.post('/busine/teacher/save', util.toFormData(this.formData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.$Message.success('修改成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        },
        save () {
            this.load = true;
            let formData = this.formData;
            this.$refs['formData'].validate((valid) => { // 表单验证
                if (valid) {
                    util.ajax.post('busine/teacher/save', util.toFormData(formData)).then(res => {
                        if (res.data.code == 200) {
                            this.$Message.success('保存成功！');
                            this.loadList();
                            this.editModal = false;
                        } else {
                            this.$Modal.error({
                                content: res.data.message || '未知错误！'
                            });
                        }
                        this.load = false;
                    });
                } else {
                    this.$Message.warning('请检查输入项！');
                    this.load = false;
                }
            });
        },
        getPermissions () {
            let permissions = this.$refs.tree.getCheckedNodes();
            let names = [];
            let id = [];
            permissions.forEach(item => {
                if (item.children.length === 0) {
                    names.push(item.title);
                    id.push(item.id);
                }
            });
            this.formData.majorsname = names.toString();
            this.formData.majorIds = id.toString();
        },
        getPermission () {
            let permission = this.$refs.treeOrg.getSelectedNodes();
            this.formData.organizeId = permission[0] ? permission[0].id : '';
            this.formData.orgname = permission[0] ? permission[0].title : '';
        }
    }
}
